package com.woniu.supermarket.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.supermarket.entity.Role;
import com.woniu.supermarket.mapper.RoleMapper;
import com.woniu.supermarket.service.IRoleService;
import com.woniu.supermarket.vo.RolePerVo;
import com.woniu.supermarket.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Override
    public List<Role> queryAllRoles() {
        return roleMapper.selectAll();
    }

    @Override
    public Role queryRoleByKey(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int modify(Role role) {
        return roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public int add(Role role) {
        return roleMapper.insert(role);
    }

    @Override
    public int remove(Integer id) {
        /*//2.解除权限与角色的绑定
        roleMapper.deletePermissionRoleById(id);*/
        //3.删除角色
        int i = roleMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public PageInfo<RoleVo> queryByPage(Integer now, Integer size, String roleName) {
        PageHelper.startPage(now,size);
        List<RoleVo> roles = roleMapper.selectByPage(roleName);
        return new PageInfo<>(roles);
    }

    @Override
    public List<Long> queryPerIdsByRoleKey(Long id) {
        return  roleMapper.selectPerIdsByRoleKey(id);
    }

    @Transactional
    @Override
    public int rolePer(RolePerVo rolePerVo) {
        //先删除当前角色的所有权限，再保存新的权限
        roleMapper.deleteFromRPByRoleId(rolePerVo.getId());
        //保存新的权限
        int i = roleMapper.insertBatchRoleAndPer(rolePerVo.getId(), rolePerVo.getCheckedIds());
        return i;
    }
}
